using System;
using System.Collections.ObjectModel;
using Prism.Mvvm;
using Prism.Commands;
using System.Windows;
using System.IO;
using System.Text.Json;
using System.Collections.Generic;
using SanmaoTools.Models;
using SanmaoTools.Common.Untils;
using System.Linq;
using Prism.Ioc;

namespace Tryit.ViewModels
{
    public class InfoSummaryViewModel : BindableBase
    {
        private string _analyst;
        private string _verifier;
        private DateTime? _archiveDate;
        private string _archiveWeight;
        private ObservableCollection<string> _analystList;
        private ObservableCollection<string> _verifierList;
        private string _shift;
        private ObservableCollection<string> _shiftList;
        private ObservableCollection<Element> _unarchivedElements;
        private Element _selectedElement;
        private ObservableCollection<Element> _selectedElements;
        private string _archiveBatchNumber;
        private string _progress;
        private DelegateCommand _archiveCommand;
        private DateTime? _startDate;
        private DateTime? _endDate;
        private DelegateCommand _searchCommand;
        private DelegateCommand _generateInfoCommand;
        private string _selectedBrandPrefix;
        private ObservableCollection<string> _brandPrefixList;

        public DelegateCommand ArchiveCommand => _archiveCommand ??= new DelegateCommand(ExecuteArchive);
        public DelegateCommand SearchCommand => _searchCommand ??= new DelegateCommand(ExecuteSearch);
        public DelegateCommand GenerateInfoCommand => _generateInfoCommand ??= new DelegateCommand(ExecuteGenerateInfo);

        public string Analyst
        {
            get => _analyst;
            set => SetProperty(ref _analyst, value);
        }

        public string Verifier
        {
            get => _verifier;
            set => SetProperty(ref _verifier, value);
        }

        public DateTime? ArchiveDate
        {
            get => _archiveDate;
            set => SetProperty(ref _archiveDate, value);
        }

        public string ArchiveWeight
        {
            get => _archiveWeight;
            set => SetProperty(ref _archiveWeight, value);
        }

        public ObservableCollection<string> AnalystList
        {
            get => _analystList;
            set => SetProperty(ref _analystList, value);
        }

        public ObservableCollection<string> VerifierList
        {
            get => _verifierList;
            set => SetProperty(ref _verifierList, value);
        }

        public string Shift
        {
            get => _shift;
            set => SetProperty(ref _shift, value);
        }

        public ObservableCollection<string> ShiftList
        {
            get => _shiftList;
            set => SetProperty(ref _shiftList, value);
        }

        public ObservableCollection<Element> UnarchivedElements
        {
            get => _unarchivedElements;
            set => SetProperty(ref _unarchivedElements, value);
        }

        public Element SelectedElement
        {
            get => _selectedElement;
            set => SetProperty(ref _selectedElement, value);
        }

        public ObservableCollection<Element> SelectedElements
        {
            get => _selectedElements;
            set => SetProperty(ref _selectedElements, value);
        }

        public string ArchiveBatchNumber
        {
            get => _archiveBatchNumber;
            set => SetProperty(ref _archiveBatchNumber, value);
        }

        public string Progress
        {
            get => _progress;
            set => SetProperty(ref _progress, value);
        }

        public DateTime? StartDate
        {
            get => _startDate;
            set => SetProperty(ref _startDate, value);
        }

        public DateTime? EndDate
        {
            get => _endDate;
            set => SetProperty(ref _endDate, value);
        }

        public string SelectedBrandPrefix
        {
            get => _selectedBrandPrefix;
            set
            {
                if (SetProperty(ref _selectedBrandPrefix, value))
                {
                    // 当选择改变时，重新加载数据
                    LoadUnarchivedElements();
                }
            }
        }

        public ObservableCollection<string> BrandPrefixList
        {
            get => _brandPrefixList;
            set => SetProperty(ref _brandPrefixList, value);
        }

        public InfoSummaryViewModel()
        {
            _analystList = new ObservableCollection<string>();
            _verifierList = new ObservableCollection<string>();
            _shiftList = new ObservableCollection<string> { "白班", "夜班" };
            _unarchivedElements = new ObservableCollection<Element>();
            _selectedElements = new ObservableCollection<Element>();
            _progress = "请输入生产进度";
            _brandPrefixList = new ObservableCollection<string>();

            // 设置默认日期范围为最近两天
            _endDate = DateTime.Now.Date;
            _startDate = _endDate.Value.AddDays(-1);

            // 从本地文件加载人员列表
            LoadPersonListFromFile();
            // 加载牌号前缀列表
            LoadBrandPrefixList();
            // 加载未归档数据
            LoadUnarchivedElements();
        }

        private void LoadPersonListFromFile()
        {
            try
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config");
                var filePath = Path.Combine(configPath, "persons.json");

                if (File.Exists(filePath))
                {
                    var json = File.ReadAllText(filePath);
                    var savedList = JsonSerializer.Deserialize<List<string>>(json);

                    if (savedList != null)
                    {
                        _analystList.Clear();
                        _verifierList.Clear();
                        foreach (var person in savedList)
                        {
                            if (!_analystList.Contains(person))
                            {
                                _analystList.Add(person);
                            }
                            if (!_verifierList.Contains(person))
                            {
                                _verifierList.Add(person);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载人员列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadBrandPrefixList()
        {
            try
            {
                using (var db = new SqlSugarHelper().GetInstance())
                {
                    // 从BrandAndStoveNumber表中获取所有不重复的牌号
                    var brands = db.Queryable<BrandAndStoveNumber>()
                        .Select(it => it.Name)
                        .Distinct()
                        .ToList();

                    // 提取牌号前缀（取前两部分，如"TP-A356.2"）
                    var prefixes = brands
                        .Select(brand =>
                        {
                            var parts = brand.Split('-');
                            return parts.Length >= 2 ? $"{parts[0]}-{parts[1]}" : parts[0];
                        })
                        .Distinct()
                        .OrderBy(p => p)
                        .ToList();

                    // 添加到列表中
                    _brandPrefixList.Clear();
                    foreach (var prefix in prefixes)
                    {
                        if (!string.IsNullOrWhiteSpace(prefix))
                        {
                            _brandPrefixList.Add(prefix);
                        }
                    }

                    // 如果有数据，选中第一个
                    if (_brandPrefixList.Count > 0)
                    {

                        if (_brandPrefixList.Contains("TP-A356.2")) { SelectedBrandPrefix = "TP-A356.2"; }
                        else SelectedBrandPrefix = _brandPrefixList[0];
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载牌号前缀列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void LoadUnarchivedElements()
        {
            try
            {
                using (var db = new SqlSugarHelper().GetInstance())
                {
                    var query = db.Queryable<Element>()
                        .Where(it => !it.IsArchived);

                    // 添加日期过滤
                    if (StartDate.HasValue)
                    {
                        query = query.Where(it => it.Date >= StartDate.Value.Date);
                    }
                    if (EndDate.HasValue)
                    {
                        query = query.Where(it => it.Date <= EndDate.Value.Date.AddDays(1).AddSeconds(-1));
                    }

                    // 添加牌号前缀过滤
                    if (!string.IsNullOrWhiteSpace(SelectedBrandPrefix))
                    {
                        query = query.Where(it => it.Brand.StartsWith(SelectedBrandPrefix));
                    }

                    var elements = query
                        .OrderByDescending(it => it.Id)
                        .ToList();

                    UnarchivedElements.Clear();
                    foreach (var element in elements)
                    {
                        UnarchivedElements.Add(element);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载未归档数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteArchive()
        {
            try
            {
                // 验证必填项
                if (string.IsNullOrWhiteSpace(Analyst))
                {
                    MessageBox.Show("请选择分析人", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (string.IsNullOrWhiteSpace(Verifier))
                {
                    MessageBox.Show("请选择审核人", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                }
                if (!ArchiveDate.HasValue)
                {
                    MessageBox.Show("请选择归档日期", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (string.IsNullOrWhiteSpace(Shift))
                {
                    MessageBox.Show("请选择班次", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                }
                if (string.IsNullOrWhiteSpace(ArchiveWeight))
                {
                    MessageBox.Show("请输入归档重量", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (SelectedElements.Count == 0)
                {
                    MessageBox.Show("请选择要归档的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                using (var db = new SqlSugarHelper().GetInstance())
                {
                    // 创建归档记录
                    var archive = new Archive
                    {
                        Analyst = Analyst,
                        Verifier = Verifier,
                        ArchiveDate = ArchiveDate.Value,
                        Shift = Shift,
                        ArchiveWeight = ArchiveWeight,
                        ArchiveBatchNumber = ArchiveBatchNumber,
                        Progress = Progress,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };

                    // 开启事务
                    db.BeginTran();
                    try
                    {
                        // 插入归档记录
                        var archiveId = db.Insertable(archive).ExecuteReturnIdentity();

                        // 更新选中元素的归档状态
                        foreach (var element in SelectedElements)
                        {
                            element.IsArchived = true;
                            element.ArchiveId = archiveId;
                            element.ArchiveTime = DateTime.Now;
                            element.ArchiveBatchNumber = ArchiveBatchNumber;
                            element.UpdateTime = DateTime.Now;
                            db.Updateable(element).ExecuteCommand();
                        }

                        // 提交事务
                        db.CommitTran();

                        MessageBox.Show("归档成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                        // 重新加载未归档数据
                        LoadUnarchivedElements();

                        // 清空选中数据
                        SelectedElements.Clear();
                        ArchiveBatchNumber = string.Empty;
                        Progress = string.Empty;

                        // 刷新成分信息列表
                        var elementManagementViewModel = (Application.Current as App)?.Container.Resolve<ElementManagementViewModel>();
                        if (elementManagementViewModel != null)
                        {
                            elementManagementViewModel.LoadElements();
                        }

                }
                catch (Exception ex)
                {
                        // 回滚事务
                        db.RollbackTran();
                        throw new Exception($"归档失败：{ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExecuteSearch()
        {
            LoadUnarchivedElements();
        }

        public void UpdateSelectedElements(IEnumerable<Element> elements)
        {
            SelectedElements.Clear();
            foreach (var element in elements)
            {
                SelectedElements.Add(element);
            }
            UpdateArchiveBatchNumber();
        }

        private void UpdateArchiveBatchNumber()
        {
            if (SelectedElements.Count > 0)
            {
                if (SelectedBrandPrefix == "TP-A356.2")
                {
                    // 按牌号和中转包次号排序
                    var sortedElements = SelectedElements
                        .OrderBy(e => e.Brand)
                        .ThenBy(e => string.IsNullOrWhiteSpace(e.Transfernumber) ? 0 : int.Parse(e.Transfernumber))
                        .ToList();
                    var minElement = sortedElements.First();
                    var maxElement = sortedElements.Last();
                    ArchiveBatchNumber = $"{minElement.Brand}-{minElement.Transfernumber}-{maxElement.Brand}-{maxElement.Transfernumber}";
                }
                else
                {
                    // 其他牌号直接拼接
                    var batchNumbers = SelectedElements
                        .Select(e => $"{e.Brand}-{e.Transfernumber}")
                        .OrderBy(b => b)
                        .ToList();
                    ArchiveBatchNumber = string.Join(",", batchNumbers);
                }
            }
            else
            {
                ArchiveBatchNumber = string.Empty;
            }
        }

        private void ExecuteGenerateInfo()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Shift))
                {
                    MessageBox.Show("请选择班次", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!ArchiveDate.HasValue)
                {
                    MessageBox.Show("请选择归档日期", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 计算班次时间范围
                DateTime shiftStart, shiftEnd;
                if (Shift == "白班")
                {
                    shiftStart = ArchiveDate.Value.Date.AddHours(8); // 早上8点
                    shiftEnd = ArchiveDate.Value.Date.AddHours(20); // 晚上8点
                }
                else
                {
                    // 夜班：当天晚上8点到第二天早上8点
                    shiftStart = ArchiveDate.Value.Date.AddHours(20); // 当天晚上8点
                    shiftEnd = ArchiveDate.Value.Date.AddDays(1).AddHours(8); // 第二天早上8点
                }

                // 查询该班次的数据
                using (var db = new SqlSugarHelper().GetInstance())
                {
                    var query = db.Queryable<Element>()
                        .Where(it => !it.IsArchived)
                        .Where(it => it.Date >= shiftStart && it.Date < shiftEnd);

                    // 添加牌号前缀过滤
                    if (!string.IsNullOrWhiteSpace(SelectedBrandPrefix))
                    {
                        query = query.Where(it => it.Brand.StartsWith(SelectedBrandPrefix));
                    }

                    var elements = query.OrderBy(it => it.Date).ToList();

                    if (elements.Count == 0)
                    {
                        MessageBox.Show("该班次没有未归档的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }


                    // 生成归档批号
                    var batchNumber = GenerateBatchNumber(elements);

                    string clipboardText;
                    if (Shift == "白班")
                    {
                        clipboardText = $"成品{ArchiveDate.Value:MM月dd日}白班工作内容：\n" +
                                      $"1、检验包次{batchNumber}共计{elements.Count}包\n" +
                                      $"2、生产进度：{Progress}";
                    }
                    else
                    {
                        clipboardText = $"成品{ArchiveDate.Value:MM月dd日}夜班工作内容：\n" +
                                      $"1、检验包次{batchNumber}共计{elements.Count}包\n" +
                                      $"2、生产进度：{Progress}\n" +
                                      $"3、归档重量：{ArchiveWeight}";
                    }

                    System.Windows.Clipboard.SetText(clipboardText);
                    MessageBox.Show("信息已复制到剪贴板", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                }
                catch (Exception ex)
                {
                MessageBox.Show($"生成信息失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private string GenerateBatchNumber(List<Element> elements)
        {
            if (elements.Count == 0) return string.Empty;

            if (SelectedBrandPrefix == "TP-A356.2")
            {
                // 按牌号和中转包次号排序
                var sortedElements = elements
                    .OrderBy(e => e.Brand)
                    .ThenBy(e => string.IsNullOrWhiteSpace(e.Transfernumber) ? 0 : int.Parse(e.Transfernumber))
                    .ToList();
                var minElement = sortedElements.First();
                var maxElement = sortedElements.Last();
                return $"{minElement.Brand}-{minElement.Transfernumber}-{maxElement.Brand}-{maxElement.Transfernumber}";
            }
            else
            {
                // 其他牌号直接拼接
                var batchNumbers = elements
                    .Select(e => $"{e.Brand}-{e.Transfernumber}")
                    .OrderBy(b => b)
                    .ToList();
                return string.Join(",", batchNumbers);
            }
        }
    }
}